import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    carts:[],
    user:[],
    mess:'',
  },
  getters:{
    total:function(state){
      var t=0;
      state.carts.forEach(function(ele){
        t+=ele.price*ele.num
      });
      return t;
    },
    count:function(state){
      var c=0;
      state.carts.forEach(function(ele){
        c+=ele.num
      });
      return c;
    },
  },
  mutations: {
    queryuser:function(state,user){
      var ele=state.user.find(function(ele){
        return ele.name==user.name//是否存在用户
      })

      if(ele) state.mess=ele.pwd//存在则返回用户信息
      else{
        return state.mess="f"
      }
    },
    reg:function(state,user){//添加用户
        state.user.push({
          ...user
        })
    },
    addCart:function(state,book){
        var ele=state.carts.find(function(ele){
          return ele.isbn===book.isbn
        });

        if(ele) ele.num++
        else{
          state.carts.push({
            isbn:book.isbn,
            bookname:book.bookname,
            price:book.price,
            num:1
          })
        }
    },
    remove:function(state,index){
      state.carts.splice(index,1)
    }
  },
  actions: {
  },
  modules: {
  }
})
